package com.zhentao.result;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;




@ControllerAdvice
@RestController
@ConditionalOnClass({ErrorController.class, HttpServletResponse.class})
public class ResultExceptionConfig implements ErrorController {



    @RequestMapping("/error")
    void error(HttpServletResponse response)throws ResultException{
        //SpringBoot的错误页面，自动进入/error,故意抛异常，让它进入下面的方法
        throw new ResultException(String.valueOf(response.getStatus()),"服务器错误");
    }

    /**
     * 业务异常 统一处理
     * @ExceptionHandler: 它能捕捉的异常类型,只要发现，自动捉到
     * 由于是RestController，所以它的返回结果将被写成JSON响应给客户端
     */
    @ExceptionHandler(value = ResultException.class)
    //@ResponseStatus(HttpStatus.OK) //之所有任何时候都返回200，是因为让客户端任何时候都能拿到消息结果
    public Result exceptionHandler(ResultException e){
        return e.getResult();
    }
}
